#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Omar Vega Ramos
# E-mail: ovruni@riseup.net
# License: GNU GPL - GNU General Public License v3.0 or later
# http://www.gnu.org/licenses/gpl.html

import argparse, csv, sys
import os.path

def csv_file(filename):
    if not filename.endswith('.csv'):
        raise argparse.ArgumentTypeError('argument input must be of type *.csv')
    return filename

parser = argparse.ArgumentParser(description='Generate the OSM file with health centers from a CSV file.')
parser.add_argument('input', type=csv_file, help='name of the input file')
parser.add_argument('-o', '--output', default='salud.osm', help='name of the output file')
args = parser.parse_args()

if os.path.isfile(args.input) == False:
    sys.exit(sys.argv[0] + ": error: the file '" + args.input + "' does not exist")

fw = open(args.output, 'w')
fw.write("<?xml version='1.0' encoding='UTF-8'?>\n")
fw.write("<osm version='0.6' upload='true' generator='JOSM'>\n")
id = -1

#row = [Código Único,EESS,Departamento,Provincia,Distrito,Dirección,Latitud,Longitud,Categoría]

with open(args.input, 'r') as fr:
    reader = csv.reader(fr)
    next(reader)
    next(reader)
    for row in reader:
        code = row[1]
        name = row[2].title()
        name = name[:1] + name[1:].replace("De ", "de ").replace("La ", "la ").replace("El ", "el ").replace("Las ", "las ").replace("Los ", "los ").replace("Del ", "del ").replace(" Y ", " y ")
        name = name.replace("'", "&apos;").replace("&", "&amp;")
        address = row[6].title().replace("'", "&apos;")
        longitude = row[7]
        latitude = row[8]
        category = row[9]

        if category == "I-1" or category == "I-2" :
            tag = 'doctors'
            name = 'Puesto de Salud ' + name

        if category == "I-3" or category == "I-4" :
            tag = 'clinic'
            name = 'Centro de Salud ' + name

        if category == "II-1" or category == "II-2" or category == "III-1" :
            tag = 'hospital'
            name = 'Hospital ' + name

        if category == "0" :
            tag = 'clinic'

        fw.write("  <node id='" + str(id) + "' action='modify' visible='true' lat='" + latitude + "' lon='" + longitude + "'>\n")
        fw.write(" <tag k='amenity' v='" + tag + "' />\n")
        fw.write(" <tag k='building' v='yes' />\n")
        fw.write(" <tag k='name' v='" + name + "' />\n")
        fw.write(" <tag k='operator' v='MINSA' />\n")
        fw.write(" <tag k='addr:street' v='" + address + "' />\n")
        if category != "0" :
            fw.write(" <tag k='pe:minsa:categoria' v='" + category + "' />\n")
        fw.write(" <tag k='pe:minsa:codigo' v='" + code + "' />\n")
        fw.write(" <tag k='source' v='www.minsa.gob.pe' />\n")
        fw.write("  </node>\n")
        id = id - 1

fw.write("</osm>")
fw.close()
sys.exit("Generated '" + args.output + "' file.")
